import serial

from PyQt5.QtCore import *
from CPlotManager import CPlotManager
from DataManager import *
from CommSetting import CCommSetting

class CScope:
    
    def __init__(self,  parent = None):
        
        self.device = serial.Serial(timeout = 0.1)   
        self.dataManager = CDataManager(self.device)
        self.plotManager = CPlotManager(self.dataManager)
        self.sampleThread = CSampleThread(self.dataManager)
        self.port = CCommSetting(self.device)
        
        self.timerInterval = 50
        self.timer = QTimer()
        self.timer.timeout.connect(self.On_Timer)    
        
        self.hold = False
        
    def UpdatePlot(self):
        
        self.plotManager.Update()
        
        
    def GetDataObject(self,  ch):
        
        return self.dataManager.GetData(ch)
        
        
    def SetFastMode(self, mode):
        
        self.dataManager.SetFastMode(mode)
        
    def Start(self):

        self.device.close()
        self.device.open()

        self.device.reset_input_buffer()
        self.device.reset_output_buffer()

        
        self.dataManager.ClearData()
        self.dataManager.StartSample()
        self.sampleThread.start()
        
        
        self.plotManager.ReInit()
        self.plotManager.Show()
        
        
        self.timer.start(self.timerInterval)
        #self.btnStart.setText('Stop')   
        #self.started = True
        
    def Stop(self):
        
        self.sampleThread.stop()
        # Wait for the thread stop
        time.sleep(0.2)
        self.device.close()
        self.timer.stop()
        self.plotManager.Finalize()
        
    def Hold(self, newState):
        self.hold = newState
        
        
    def On_Timer(self): 
        
        #self.dataManager.GetData()
        
        if self.hold == False:
            self.plotManager.Update()
                
        #self.pgsDataBuf.setValue(self.dataManager.dataList[0].length() * 100 /len(self.dataManager.dataList[0].data))
    
    def GetCurveView(self):
        return self.plotManager.GetWin()
        
        
    def Finalize(self):
        self.plotManager.Finalize()
        
        
    def ShowCommSetting(self):
        self.port.Show()

    def UpdateDataAttributes(self, ch, slaveAddr,  name, addr, size, sign, scale, offset):
        self.dataManager.UpdateChProperties(ch, slaveAddr,  name, addr, size, sign, scale, offset)
